#include "browser.h"
#include "cookiejar.h"
#include "QWebSettings"
#include "../activite/webcollector.h"

Browser* Browser::m_browser = NULL;

Browser::Browser(QObject * /*parent*/)
    //: QObject(QCoreApplication::instance())
    : QObject(0)
    , m_defaultPageSettings(0)
{
}


Browser::~Browser() 
{
    qDeleteAll(m_pages);
    m_pages.clear();
    if (m_defaultPageSettings)
        delete m_defaultPageSettings;
}

void Browser::onInitialized()
{
}

void Browser::init()
{
    // Initialize the CookieJar
    //CookieJar::instance("./cookie.txt");
    CookieJar::instance();

    if (!m_defaultPageSettings) {
        m_defaultPageSettings = new Setting::PageSetting();
        m_defaultPageSettings->set(PAGE_SETTINGS_JS_ENABLED, QVariant::fromValue(!WebCollector::instance()->isStatic()));
    }
}

Browser* Browser::instance()
{
    if (m_browser == NULL) {
        m_browser = new Browser();
        m_browser->init();
    }
    return m_browser;
}

WebPageAdapter *Browser::createWebPage(PageProtocol *client, WebSpiderRequest *req)
{
    WebPage *page = new WebPage(this);
    m_pages.append(page);

    WebPageAdapter *adapter = new WebPageAdapter(page, client, req, this);
    return adapter;
}

Operator* Browser::appendWebPage(WebPage *page)
{
    m_pages.append(page);
    return WebCollector::instance()->createActiviteWithCompletedWebPage(page);
}

QVariantMap& Browser::defaultPageSettings()
{
    if (!m_defaultPageSettings) {
        m_defaultPageSettings = new Setting::PageSetting();
    }

    m_defaultPageSettings->set(PAGE_SETTINGS_JS_ENABLED, QVariant::fromValue(!WebCollector::instance()->isStatic()));
    return m_defaultPageSettings->setting();
}

bool Browser::destoryWebPage(WebPageAdapter *adapter)
{
    if (!adapter)
        return false;

    if (!adapter->page())
        return false;

    m_pages.removeOne(adapter->page());

    adapter->release();

    adapter = NULL;

    return true;
}



